<template>
  <div class="goods">
    <div class="menu-container" ref="menu-container" @touchmove="menuOnTouchMove">
      <ul class="menu">
        <li v-for="(category, index) in menu"
          :class="{ 'current': (currentIndex == index) }">
          <a href="javascript:;" @click="selectMenu(index, $event)">{{category.name}}</a>
        </li>
      </ul>
    </div>
    <div class="foods-container" ref="foods-container" @scroll="foodsContainerOnScroll">
      <div class="foods-list">
        <dl class="foods" v-for="category in menu">
          <dt>{{category.name}}</dt>
          <dd v-for="food in category.foods">
            <food-item :food="food" @click="showItem"></food-item>
          </dd>
        </dl>
      </div>
    </div>

    <item-detail v-if="activedGoods" :item="activedGoods"
      @close="activedGoods = null"></item-detail>
    <cart :goods="selectedGoods" :minPrice="80" @buy="buyItem"></cart>
  </div>
</template>

<script>
// import Vue from 'vue'
import BScroll from 'better-scroll'
import Cart from 'components/cart/Cart'
import ItemDetail from 'components/goods/ItemDetail'
import FoodItem from './FoodItem'

export default {
  name: 'Goods',

  components: {
    FoodItem,
    ItemDetail,
    Cart
  },

  data() {
    return {
      menu: [],
      selectedGoods: [],

      foodsListHeight: [],
      scrollY: 0,

      activedGoods: null
    }
  },

  computed: {
    currentIndex() {
      for (let i = 0; i < this.foodsListHeight.length; i++) {
        let heightStart = this.foodsListHeight[i]
        let heightEnd = this.foodsListHeight[i + 1]
        if (!heightEnd || (this.scrollY >= heightStart && this.scrollY < heightEnd)) {
          return i
        }
      }
      return 0
    },

    selectedGoods() {
      const goods = []
      this.menu.forEach((category) => {
        category.foods.forEach((food) => {
          if (food.count > 0) {
            goods.push(food)
          }
        })
      })
      return goods
    }
  },

  // watch: {
  //   selectedGoods(val) {
  //     console.log('selectedGoods change', val)
  //   }
  // },

  created() {
    this.$http.get('/api/menu').then((response) => {
      // console.log('response', response)
      let res = response.data
      if (res.error) {
        console.log('error', res)
      }
      else {
        // console.log('success', res)
        this.menu = this.formatData(res.data)
        // this.menu = res.data
        this.$nextTick(() => {
          // this.initScroll()
          this.getFoodsListHeight()
        })
      }
    })
  },

  methods: {
    formatData(data) {
      data.forEach((category) => {
        category.foods.forEach((food) => {
          food = this.formatFoodData(food)
        })
      })
      return data
    },

    formatFoodData(food) {
      food.image = this.formatImageSrc(food.image_path, '140x140')
      food.sales = parseInt(food.month_sales) || 0
      food.price = food.specfoods[0].price
      food.count = 0
    },

    formatImageSrc(path, size) {
      let path0 = path.substr(0, 1) + '/'
      let path1 = path.substr(1, 2) + '/'
      let path2 = path.substring(3, path.length)
      let url = 'http://fuss10.elemecdn.com/' +
        path0 + path1 + path2 + '.jpeg?imageMogr/thumbnail/' +
        // size + '/format/webp/quality/85'
        size + '/quality/85'
      return url
    },

    initScroll() {
      this.menuScroll = new BScroll(this.$refs['menu-container'], {
        click: true
      })

      this.foodsScroll = new BScroll(this.$refs['foods-container'], {
        click: true,
        probeType: 3
      })

      this.foodsScroll.on('scroll', (pos) => {
        this.scrollY = Math.abs(Math.round(pos.y))
      })
    },

    foodsContainerOnScroll(evt) {
      this.scrollY = this.$refs['foods-container'].scrollTop
      console.log('foodsContainerOnScroll', this.scrollY)
    },

    getFoodsListHeight() {
      let groups = this.$refs['foods-container'].getElementsByClassName('foods')
      let height = 0
      this.foodsListHeight.push(height)

      for (let i = 0; i < groups.length; i++) {
        height += groups[i].clientHeight
        this.foodsListHeight.push(height)
      }
      console.log('foodsListHeight', this.foodsListHeight)
    },

    // selectMenu(index, evt) {
    //   if (!evt._constructed) {
    //     return
    //   }
    //   console.log('selectMenu', index)
    //
    //   let groups = this.$refs['foods-container'].getElementsByClassName('foods')
    //   let el = groups[index]
    //   this.foodsScroll.scrollToElement(el, 300)
    // },

    selectMenu(index) {
      console.log('selectMenu', index)
      this.$refs['foods-container'].scrollTop = this.foodsListHeight[index]
    },

    selectFood(food) {
      this.selectedGoods.forEach((goods) => {
        if (goods.name === food.name) {
          goods.count = food.count
        }
        else {
          this.selectedGoods.push(goods)
        }
      })
      // console.log('selectFood', food, this.selectedGoods)

      // Vue.set('selectedGoods', this.selectedGoods)
    },

    menuOnTouchMove(evt) {
      // console.log('onTouchStart', evt)
      const $container = document.getElementsByClassName('menu-container')[0]
      const $content = document.getElementsByClassName('menu')[0]
      console.log($container.scrollTop, $container.offsetHeight, $content.offsetHeight)

      // if ($container.scrollTop === ($content.offsetHeight - $container.offsetHeight)) {
      //   // evt.preventDefault()
      // }

      if ($container.offsetHeight >= $content.offsetHeight) {
        evt.preventDefault()
      }
    },

    showItem(item) {
      console.log('showItem', item)
      this.activedGoods = item
    },

    buyItem(item) {
      console.log('buyItem', item)
      this.selectedGoods.push(item)
    }
  }
}
</script>

<style lang="less" scoped>
.goods {
  display: flex;
  position: absolute;
  top: 140px;
  bottom: 0;
  width: 100%;
  overflow: hidden;

  .menu-container {
    flex: 0 0 80px;
    width: 80px;
    background-color: #f3f5f7;

    overflow: auto;
    -moz-overflow-scrolling: touch;
    -webkit-overflow-scrolling: touch;
    overflow-scrolling: touch;
  }

  .foods-container {
    flex: 1;
    overflow: auto;
    -moz-overflow-scrolling: touch;
    -webkit-overflow-scrolling: touch;
    overflow-scrolling: touch;
  }

  .menu {
    list-style: none;
    padding: 0;
    margin: 0;

    li {
      padding: 0;
      margin: 0;
      border-bottom: 1px solid #ddd;

      a {
        display: block;
        padding: 15px 10px;
        font-size: 12px;
      }
    }

    li.current {
      a {
        color: #ff3366;
        background-color: #fff;
      }
    }
  }

  .foods-list {
    padding-bottom: 200px;
  }

  .foods {
    padding: 0;
    margin: 0;

    & > dt {
      padding: 5px 10px;
      border-left: 2px solid #d9dde1;
      background-color: #f3f5f7;
      font-weight: normal;
      font-size: 12px;
      color: rgb(147, 153, 195);
    }

    & > dd {
      padding: 0 15px;
      margin: 0;
    }
  }
}
</style>
